import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Button,
  Box,
  Typography,
} from '@mui/material';
import { usePost } from '../contexts/PostContext';
import { Post } from '../types';

interface EditPostDialogProps {
  open: boolean;
  post: Post | null;
  onClose: (edited?: boolean, updatedPost?: Post) => void;
}

export const EditPostDialog: React.FC<EditPostDialogProps> = ({
  open,
  post,
  onClose,
}) => {
  const { updatePost } = usePost();
  const [content, setContent] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (post) {
      setContent(post.postContent);
    }
  }, [post]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!post || !content.trim()) {
      setError('内容不能为空');
      return;
    }

    try {
      setLoading(true);
      setError(null);
      // 获取更新后的帖子数据
      const updatedPost = await updatePost(post.postId, content);
      
      // 传递编辑成功的标志和更新后的帖子数据
      onClose(true, updatedPost);
    } catch (err) {
      setError('更新帖子失败，请重试');
      console.error('更新帖子错误:', err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
      <DialogTitle>编辑帖子</DialogTitle>
      <Box component="form" onSubmit={handleSubmit}>
        <DialogContent>
          <TextField
            fullWidth
            multiline
            rows={4}
            label="内容"
            value={content}
            onChange={(e) => setContent(e.target.value)}
            error={Boolean(error)}
            helperText={error}
            disabled={loading}
            sx={{ mb: 2 }}
          />
          {error && (
            <Typography color="error" variant="body2">
              {error}
            </Typography>
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => onClose()} disabled={loading}>
            取消
          </Button>
          <Button type="submit" variant="contained" disabled={loading}>
            保存
          </Button>
        </DialogActions>
      </Box>
    </Dialog>
  );
};